import sqlite3
import os
from datetime import datetime


def getLatestDownload(chrome_history_path=r"H:\download\chrome\profile\Default\History"):
    # Chrome下载历史数据库文件路径

    # 连接数据库
    connection = sqlite3.connect(chrome_history_path)
    cursor = connection.cursor()

    # # 获取表格中的列名
    # cursor.execute("PRAGMA table_info(downloads_url_chains)")
    # columns = cursor.fetchall()
    #
    # # 打印列名
    # print("Column Names:")
    # for column in columns:
    #     print(column[1])

    # 获取下载记录
    cursor.execute("""
         SELECT downloads.target_path,url_chains.url,url_chains.id FROM downloads 
         LEFT JOIN downloads_url_chains AS url_chains ON downloads.id = url_chains.id ORDER BY downloads.start_time DESC limit 2
        """)

    rows = cursor.fetchall()
    # 关闭连接
    cursor.close()
    connection.close()

    # print(rows)
    # 打印下载记录
    # print(
    #     "ID\tURL\t\t\t\t\t\t\t\t\t\t\t\t\tPath\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tStart Time")
    # print("=" * 150)

    if len(rows) > 0:
        localFilePath = rows[0][0]
        downloadUrl = rows[0][1]
        for row in rows:
            localPath = row[0]
            url = row[1]
            if (localPath == localFilePath):  # 地址相同的话则取下载地址更长的链接因为有些url会有重定向，重定向的地址通常更长所以这样判断
                if (len(url) > len(downloadUrl)):
                    downloadUrl = url
        # localFilePath, url, id = rows[len(rows) - 1]  # 有可能有转定向的地址所以取最后一个地址
        # localFilePath, url, id = rows[0]  # 有可能有转定向的地址所以取最后一个地址

        return localFilePath, downloadUrl

    return "", ""


if __name__ == '__main__':
    localFilePath, url = getLatestDownload(
        chrome_history_path=r"H:\download\chrome\profile\Default\History")
    print(localFilePath, url)
